package stm.liyiruo.sign2pdf.service.impl;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.springframework.beans.factory.annotation.Autowired;
import stm.liyiruo.sign2pdf.config.PDFConfig;
import stm.liyiruo.sign2pdf.service.IPDFService;
import stm.liyiruo.sign2pdf.util.PDFUtils;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * @author liyiruo
 * @Description
 * @Date 2021/8/11 下午3:45
 */
public class PDFServiceImpl implements IPDFService {
    public PDFConfig getConfig() {
        return config;
    }

    public void setConfig(PDFConfig config) {
        this.config = config;
    }

    @Autowired
    private PDFConfig config;

    @Override
    public String signPdfBase64(PDFConfig config) throws IOException, DocumentException {
        //解码2个文件
        byte[] base64imgArr = Base64.getDecoder().decode(config.getSignImgBase64());

        byte[] base64pdfArr = Base64.getDecoder().decode(config.getPdfBase64());
        //输出的流
        ByteArrayOutputStream ops = new ByteArrayOutputStream();
        //加载文件
        PdfReader reader = new PdfReader(base64pdfArr);
        PdfStamper stamper = new PdfStamper(reader, ops);
        //设置操作第几页pdf
        PdfContentByte page = stamper.getOverContent(config.getPageNum());
        Image image = Image.getInstance(base64imgArr);
        //设置图片在页面中的坐标
        image.setAbsolutePosition(config.getAbsoluteX(), config.getAbsoluteY());
        //设置图片的宽度和高度
        image.scaleAbsolute(config.getNewWidth(), config.getNewHeight());
        page.addImage(image);
        stamper.close();
        reader.close();

        //String encode = new BASE64Encoder().encode(ops.toByteArray());
        byte[] bytes = Base64.getEncoder().encode(ops.toByteArray());
        String s = new String(bytes);
        return s;
    }

    /**
     * 将base64文件字符串 写到指定的位置
     *
     * @param base64Str 文件base64的字符串
     * @param dist      文件的输出全路径
     * @return
     */
    @Override
    public void saveBase64ToDist(String base64Str, String dist) throws Exception {
        byte[] decodeBuffer = Base64.getDecoder().decode(base64Str);
        PDFUtils.saveFile(dist, decodeBuffer);
    }

    /**
     * 将指定位置的文件读成base64字符串,并返回
     *
     * @param src 文件全路径
     * @return base64字符串
     */
    @Override
    public String getBase64StrFromSrc(String src) {
        String base64Str = PDFUtils.getBase64FromFile(src);
        return base64Str;
    }

    @Override
    public PDFConfig getData() {
        return this.config;
    }

}
